﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedicalManagementSystem.Helpers {
    /*
     * Чтобы работало, надо добавить роли именно с такими названиями.
     */
    public enum UserRoles {
        AdminRole = 1,
        RegistratorRole = 2,
        DoctorRole = 4,
        ArchiverRole = 8,
        StatisticRole = 16
    }
    public class EnumAuthorizeAttribute : AuthorizeAttribute {
        public new UserRoles Roles;

        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            string[] userRoles = System.Web.Security.Roles.GetRolesForUser();
            foreach (string userRole in userRoles) {
                UserRoles role = (UserRoles)Enum.Parse(typeof(UserRoles), userRole);
                if ((UserRoles.AdminRole & role) == role)
                    return true;
                if ((Roles & role) == role) {
                    return true;
                }
            }

            return false;
        }
    }
}